package com.xy.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NovelCatalogUtil {
		public static Map<String, List<String>> getCatalogs(String filePath) throws IOException {
				String src = "";
				File file = new File(filePath);
				Map<String, List<String>> map = new HashMap<>();
				InputStream fis = null;
				if (file.exists() && file.exists()) {
						try {
								map = cutFile(filePath);
						} catch (IOException e) {
								e.printStackTrace();
						} finally {
								if (fis != null) {
										fis.close();
								}
						}
				} else throw new IOException("文件不存在或不是文件");

				return map;
		}

		public static Map<String, List<String>> cutFile(String path) throws IOException {
				//定义一个字符串用来储存读入的小说内容
				String src = "";
				//文件输入流，个人喜欢用流
				InputStream fis = null;
				try {
						//从指定路径读取小说
						fis = new FileInputStream(path);
						byte[] bt = new byte[5440];//一个页面5440字节
						int i = 0;
						//for循环读取数据，保存在src中
						while ((i = fis.read(bt)) != -1) {
								String temp = new String(bt, getFileEncode(path));
								//System.out.println(temp);
								src += temp;
						}
				} catch (Exception e) {
						e.printStackTrace();
				} finally {
						//记得关闭流
						if (fis != null) {
								fis.close();
						}

				}
				Map<String, List<String>> map = cutCatlog(src, "2", "");
				return map;
		}

		/*
		 * src:小说的内容
		 * model：是否生成章节文件
		 * bookname：小说名
		 * */
		public static Map<String, List<String>> cutCatlog(String src, String model, String bookname) {
				Map<String, List<String>> map = new HashMap<>();
				//匹配规则
				String pest = "(正文){0,1}(\\s|\\n)(第)([\\u4e00-\\u9fa5a-zA-Z0-9]{1,7})[章][^\\n]{1,35}(|\\n)";//[章节卷集部回]( )
				//替换规则
				String washpest = "(PS|ps)(.)*(|\\n)";
				//将小说内容中的PS全部替换为“”
				src = src.replaceAll(washpest, "");
				//list用来储存章节内容
				List<String> list = new ArrayList<>();
				List<String> namelist = new ArrayList<String>();
				//根据匹配规则将小说分为一章一章的，并存到list
				for (String s : src.split(pest)) {
						list.add(s);
				}
				//System.out.println("size" + src.split(pest).length);
				//java正则匹配
				Pattern p = Pattern.compile(pest);
				Matcher m = p.matcher(src);
				int i = 1, j = 1;
				//存拼接章节内容和章节名后的内容
				List<String> newlist = new ArrayList<>();
				//临时字符串
				String newstr = null;
				//循环匹配
				while (m.find()) {
						newstr = "";
						//替换退格符
						String temp = m.group(0).replace(" ", "").replace("\r", "");
						if (i == list.size())
								break;
						//拼接章节名和内容
						newstr = temp + list.get(i);
						i++;
						newlist.add(newstr);
						//添加章节名在list,过滤干扰符号
						temp = temp.replaceAll("[（](.)*[）]", "").replace("：", "");
						temp = temp.replace("\\", "").replace("/", "").replace("|", "");

						temp = temp.replace("?", "").replace("*", "").replaceAll("[(](.)*[)]", "");
						//System.out.println("j=" + j + " temp=" + temp + ".txt");
						j++;
						namelist.add(temp.replace("\n", ""));
						temp = "";
				}
				if (model != null && model.equals("1")) {
						//2.创建目录
						File file = new File("E:/BookFile/" + bookname);
						if (!file.exists()) {
								file.mkdir();
						}
						String filedir = file.getPath();

						//循环生成章节TXT文件
						for (i = 0; i < newlist.size(); i++) {
								//System.out.println("catname="+filedir+File.separator+namelist.get(i));
								//2.在目录下创建TXT文件
								StringBuffer ctl = new StringBuffer(namelist.get(i));
								String bloodbath = filedir + File.separator + ctl.append(".txt");
								//System.out.println(bloodbath);

								File book = new File(bloodbath);

								FileWriter fr = null;
								try {
										fr = new FileWriter(book);
										fr.write(newlist.get(i));
								} catch (Exception e) {
										e.printStackTrace();
								} finally {
										try {
												if (fr != null) {
														fr.close();
												}
										} catch (IOException e) {
												e.printStackTrace();
										}
								}
						}
				}
				//返回章节和目录
				if (model.equals("2")) {
						map.put("catalogs", namelist);
						map.put("catalogContent", newlist);
				}
				return map;

		}

		public static String getFileEncode(String filePath) throws IOException {
//				String charsetName = "";
//				try {
//						File file = new File(filePath);
//						CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
//						detector.add(new ParsingDetector(false));
//						//添加三种编码格式
//						detector.add(JChardetFacade.getInstance());
//						detector.add(ASCIIDetector.getInstance());
//						detector.add(UnicodeDetector.getInstance());
//						java.nio.charset.Charset charset = null;
//						charset = detector.detectCodepage(file.toURI().toURL());
//						if (charset != null) {
//								charsetName = charset.name();
//						} else {
//								charsetName = "UTF-8";
//						}
//				} catch (Exception ex) {
//						ex.printStackTrace();
//				}
//				return charsetName;
				String code = null;
				BufferedInputStream bin = null;
				try {
						bin = new BufferedInputStream(new FileInputStream(filePath));
						int p = (bin.read() << 8) + bin.read();
						bin.close();
						code = null;

						switch (p) {
								case 0xefbb:
										code = "UTF-8";
										break;
								case 0xfffe:
										code = "Unicode";
										break;
								case 0xfeff:
										code = "UTF-16BE";
										break;
								default:
										code = "GBK";
						}
				} catch (IOException e) {
						e.printStackTrace();
				} finally {
						if (bin != null) {
								bin.close();
						}
				}

				return code;
		}

}
